package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Announcement;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private AnnouncementApi announcementApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    /**
     * 根据环信id查询用户详情
     */
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        //1、根据环信id查询用户
        User user = userApi.findByHuanxin(huanxinId);
        //2、根据用户id查询用户详情
        UserInfo userInfo = userInfoApi.findById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //添加好友关系
    public void contacts(Long friendId) {
        //1、将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + friendId);
        if(!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
        //2、如果注册成功，记录好友关系到mongodb
        friendApi.save(UserHolder.getUserId(),friendId);
    }

    //分页查询联系人列表
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //1、调用API查询当前用户的好友数据 -- List<Friend>
        List<Friend> list = friendApi.findByUserId(UserHolder.getUserId(),page,pagesize);
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //2、提取数据列表中的好友id
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //3、调用UserInfoAPI查询好友的用户详情
        UserInfo info = new UserInfo();
        info.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
        //4、构造VO对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if(userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    public void deleteFriendByFriendId(Long likeUserId, Long userId) {
        Boolean result = huanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + userId,
                Constants.HX_USER_PREFIX + likeUserId);
        if (!result){
            throw new BusinessException(ErrorResult.error());
        }
        friendApi.deleteFriendByFriendId(UserHolder.getUserId(),likeUserId);
    }


    //点赞列表
    public PageResult getLikeList(int page, int pagesize) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //根据用户id，评论类型，分页条件获取comment集合
        List<Comment> commentList = commentApi.getCommentsByPublishUserId(
                userId, CommentType.LIKE.getType(), page,pagesize);
        //先判断是否查询到结果
        if(CollUtil.isEmpty(commentList)){
            //如果为空，返回空的PageResult
            return new PageResult();
        }
        //如果不为空，提取出用户ids
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        //调用userInfoApi根据ids查询返回map，查询条件为空
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
        //用新的MessageListVo集合接收
        List<MessageListVo> messageListVos = new ArrayList<>();
        //遍历commentsByPublishUserId
        for (Comment comment : commentList) {
            Long commentUserId = comment.getUserId();
            UserInfo userInfo = userInfoMap.get(commentUserId);
            if(userInfo!=null){
                MessageListVo messageListVo = MessageListVo.init(userInfo,comment);
                messageListVos.add(messageListVo);
            }
        }
        return new PageResult(page,pagesize,0,messageListVos);
    }


    //评论列表
    public PageResult getCommentList(int page, int pagesize) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //根据用户id，评论类型，分页条件获取comment集合
        List<Comment> commentList = commentApi.getCommentsByPublishUserId(
                userId, CommentType.COMMENT.getType(), page,pagesize);
        //先判断是否查询到结果
        if(CollUtil.isEmpty(commentList)){
            //如果为空，返回空的PageResult
            return new PageResult();
        }
        //如果不为空，提取出用户ids
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        //调用userInfoApi根据ids查询返回map，查询条件为空
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
        //用新的MessageListVo集合接收
        List<MessageListVo> messageListVos = new ArrayList<>();
        //遍历commentsByPublishUserId
        for (Comment comment : commentList) {
            Long commentUserId = comment.getUserId();
            UserInfo userInfo = userInfoMap.get(commentUserId);
            if(userInfo!=null){
                MessageListVo messageListVo = MessageListVo.init(userInfo,comment);
                messageListVos.add(messageListVo);
            }
        }
        return new PageResult(page,pagesize,0,messageListVos);
    }



    //喜欢列表
    public PageResult getLoveList(int page, int pagesize) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //根据当前用户id，评论类型是喜欢3，调用api查询返回comment对象
        List<Comment> commentsByPublishUserId = commentApi.getCommentsByPublishUserId(
                userId, CommentType.LOVE.getType(), page, pagesize);
        //如果查询结果为空
        if(CollUtil.isEmpty(commentsByPublishUserId)){
            //返回空pageResult
            return new PageResult();
        }
        //如果不为空，提取出用户ids
        List<Long> userIds = CollUtil.getFieldValues(commentsByPublishUserId, "userId", Long.class);
        //调用userInfoApi根据ids查询返回map，查询条件为空
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
        //用新的MessageListVo集合接收
        List<MessageListVo> messageListVos = new ArrayList<>();
        //遍历commentsByPublishUserId
        for (Comment comment : commentsByPublishUserId) {
            Long commentUserId = comment.getUserId();
            UserInfo userInfo = userInfoMap.get(commentUserId);
            if(userInfo!=null){
                MessageListVo messageListVo = MessageListVo.init(userInfo,comment);
                messageListVos.add(messageListVo);
            }
        }


        return new PageResult(page,pagesize,0,messageListVos);
    }

    //公告列表
    public PageResult getannouncementsList(int page, int pagesize) {
        //1.获取公告列表
        List<Announcement> announcements = announcementApi.getAnnouncementApi(page,pagesize);
        //判断是否为空
        if (CollUtil.isEmpty(announcements)){
            //为空的话返回一个新的PageResult
            return new PageResult();
        }
        //不为空返回数据列表
        return new PageResult(page,pagesize,0,announcements);
    }
}